// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: "defend-grgsv"
})

const db = cloud.database()
const commentCollection = db.collection("messageData")

// 云函数入口函数
exports.main = async (event, context) => {
  console.log("传进来的参数：", event)

  let totalCount = await commentCollection.aggregate()
    .match({
      publishID: event.id
    })
    .lookup({
      from: 'userInfo',
      localField: 'messageID',
      foreignField: '_openid',
      as: 'userinfo',
    }).count('totalCount').end()
  console.log("totalCount", totalCount)


  let comments = await commentCollection.aggregate()
    .match({
      publishID: event.id
    })
    .lookup({
      from: 'userInfo',
      localField: 'messageID',
      foreignField: '_openid',
      as: 'userinfo',
    }).sort({
      messageDate: -1,
      _id: 1
    })
    .skip((event._page - 1) * event._pageSize)
    .limit(event._pageSize)
    .end()

  var totalPage = 0
  if (totalCount.list[0]) {
    let counts = totalCount.list[0].totalCount
    totalPage = counts === 0 ? 0 : counts <= event._pageSize ? 1 : counts % event._pageSize == 0 ? parseInt(counts / event._pageSize) : parseInt(counts / event._pageSize) + 1
  } else {
    totalPage = 0
  }

  return { totalPage, comments }
}